﻿using System;
using System.Text;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;
using System.Web.UI;
using TST.SharePoint.Shared;
using Microsoft.SharePoint.WebPartPages;
using System.IO;

namespace TST.WebParts
{
    [ViewStateModeById]
    class ListSelectEditorPart : EditorPart
    {
        private Exception _error;
        private TextBox _listUrl;
        private Button _selectList;
        private DropDownList _selectDisplayField;
        private DropDownList _selectValueField;
        private RadioButtonList _selectDisplayMode;
        private CheckBox _selectDistinct;
        private TextBox _cssClass;
        private CheckBox _debug;
        private DropDownList _selectXSLT;
        private TextBox _selectDropDownFirstItem;
        private CheckBox _selectDisplayWebPartTitle;

        public ListSelectEditorPart(string webPartID)
        {
            this.ID = "ListSelectEditorPart" + webPartID;
            this.Title = "List Item Filter Options";
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            HtmlTable table = new HtmlTable();
            table.CellPadding = 5;
            table.CellSpacing = 3;
            Controls.Add(table);

            HtmlTableRow rowlist = new HtmlTableRow();
            table.Controls.Add(rowlist);
            HtmlTableCell cellList = new HtmlTableCell();
            rowlist.Controls.Add(cellList);
            Label labelList = new Label();
            cellList.Controls.Add(labelList);
            cellList.Controls.Add(new LiteralControl("<br />"));
            _listUrl = new TextBox();
            cellList.Controls.Add(_listUrl);
            if (DatasourceContentType.IsWSS)
            {
                _listUrl.Width = 180;
                labelList.Text = "Enter the url to a list";
                cellList.Controls.Add(new LiteralControl("<br />"));
                _selectList = new Button();
                _selectList.Width = 50;
                _selectList.Click += new EventHandler(_selectList_Click);
                _selectList.Text = "Load";
                cellList.Controls.Add(_selectList);
                cellList.Controls.Add(new LiteralControl("<br />"));
                Label description = new Label();
                description.Text = String.Format("Enter the url to your list and click the Load button.<br> For example: '/sites/TeamSite1/Tasks'. This has to be the url <i>relative to your web application</i>, followed by the <b>title</b> of the list, or the <b>name</b> of the rootfolder of the list.<br />The relative url for the current site is: <i>{0}</i>.", SPContext.Current.Web.ServerRelativeUrl);
                cellList.Controls.Add(description);
            }
            else
            {
                labelList.Text = "Select a list";
                _listUrl.Width = 180;
                _listUrl.TextChanged += new EventHandler(_listUrl_TextChanged);
                _selectList = new Button();
                _selectList.Width = 20;
                _selectList.OnClientClick = "javascript:launchPicker();";
                _selectList.Text = "...";
                cellList.Controls.Add(_selectList);
            }

            HtmlTableRow rowDisplay = new HtmlTableRow();
            table.Controls.Add(rowDisplay);
            HtmlTableCell cellDisplay = new HtmlTableCell();
            rowDisplay.Controls.Add(cellDisplay);
            Label labelDisplay = new Label();
            labelDisplay.Text = "Field to be displayed";
            cellDisplay.Controls.Add(labelDisplay);
            cellDisplay.Controls.Add(new LiteralControl("<br />"));
            _selectDisplayField = new DropDownList();
            _selectDisplayField.Width = 200;
            cellDisplay.Controls.Add(_selectDisplayField);

            HtmlTableRow rowValue = new HtmlTableRow();
            table.Controls.Add(rowValue);
            HtmlTableCell cellValue = new HtmlTableCell();
            rowValue.Controls.Add(cellValue);
            Label labelValue = new Label();
            labelValue.Text = "Field to be sent as filter value";
            cellValue.Controls.Add(labelValue);
            cellValue.Controls.Add(new LiteralControl("<br />"));
            _selectValueField = new DropDownList();
            _selectValueField.Width = 200;
            cellValue.Controls.Add(_selectValueField);

            HtmlTableRow rowDistinct = new HtmlTableRow();
            table.Controls.Add(rowDistinct);
            HtmlTableCell cellDistinct = new HtmlTableCell();
            rowDistinct.Controls.Add(cellDistinct);
            Label labelDistinct = new Label();
            labelDistinct.Text = "Just display distinct values";
            cellDistinct.Controls.Add(labelDistinct);
            _selectDistinct = new CheckBox();
            cellDistinct.Controls.Add(_selectDistinct);

            HtmlTableRow rowDIsplayMode = new HtmlTableRow();
            table.Controls.Add(rowDIsplayMode);
            HtmlTableCell cellDIsplayMode = new HtmlTableCell();
            rowDIsplayMode.Controls.Add(cellDIsplayMode);
            Label labelDIsplayMode = new Label();
            labelDIsplayMode.Text = "Display mode";
            cellDIsplayMode.Controls.Add(labelDIsplayMode);
            cellDIsplayMode.Controls.Add(new LiteralControl("<br />"));
            _selectDisplayMode = new RadioButtonList();
            _selectDisplayMode.Items.Add(new ListItem("Drop down", "0"));
            _selectDisplayMode.Items.Add(new ListItem("Radio button", "1"));
            _selectDisplayMode.Items.Add(new ListItem("Checkbox list", "2"));
            _selectDisplayMode.Items.Add(new ListItem("Tag Cloud", "3"));
            _selectDisplayMode.Items.Add(new ListItem("XSLT Transformation", "4"));
            cellDIsplayMode.Controls.Add(_selectDisplayMode);

            HtmlTableRow rowXSLT = new HtmlTableRow();
            table.Controls.Add(rowXSLT);
            HtmlTableCell cellXSLT = new HtmlTableCell();
            rowXSLT.Controls.Add(cellXSLT);
            Label labelXSLT = new Label();
            labelXSLT.Text = "XSLT Stylesheet";
            cellXSLT.Controls.Add(labelXSLT);
            cellXSLT.Controls.Add(new LiteralControl("<br />"));
            _selectXSLT = new DropDownList();
            _selectXSLT.Items.Add(new ListItem("-- Select a style sheet --", string.Empty));
            _selectXSLT.Width = 200;
            cellXSLT.Controls.Add(_selectXSLT);

            ListItemFilter webPart = WebPartToEdit as ListItemFilter;
            if (System.IO.Directory.Exists(webPart.ResourcePath))
            {
                DirectoryInfo directoryInfo = new DirectoryInfo(webPart.ResourcePath);
                foreach (FileInfo fileInfo in directoryInfo.GetFiles("*.xslt"))
                {
                    ListItem item = new ListItem(fileInfo.Name, fileInfo.Name);
                    _selectXSLT.Items.Add(item);
                }
            }

            HtmlTableRow rowDisplayTitle = new HtmlTableRow();
            table.Controls.Add(rowDisplayTitle);
            HtmlTableCell cellDisplayTitle = new HtmlTableCell();
            rowDisplayTitle.Controls.Add(cellDisplayTitle);
            Label labelDisplayTitle = new Label();
            labelDisplayTitle.Text = "Display web part title";
            cellDisplayTitle.Controls.Add(labelDisplayTitle);
            _selectDisplayWebPartTitle = new CheckBox();
            cellDisplayTitle.Controls.Add(_selectDisplayWebPartTitle);

            HtmlTableRow rowDropDownFirstItem = new HtmlTableRow();
            table.Controls.Add(rowDropDownFirstItem);
            HtmlTableCell cellDropDownFirstItem = new HtmlTableCell();
            rowDropDownFirstItem.Controls.Add(cellDropDownFirstItem);
            Label labelOneDropDownFirstItem = new Label();
            labelOneDropDownFirstItem.Text = "If display mode is dropdown";
            cellDropDownFirstItem.Controls.Add(labelOneDropDownFirstItem);
            cellDropDownFirstItem.Controls.Add(new LiteralControl("<br />"));
            Label labelTwoDropDownFirstItem = new Label();
            labelTwoDropDownFirstItem.Text = "Enter first item text";
            cellDropDownFirstItem.Controls.Add(labelTwoDropDownFirstItem);
            cellDropDownFirstItem.Controls.Add(new LiteralControl("<br />"));
            _selectDropDownFirstItem = new TextBox();
            cellDropDownFirstItem.Controls.Add(_selectDropDownFirstItem);

            HtmlTableRow rowCssClass = new HtmlTableRow();
            table.Controls.Add(rowCssClass);
            HtmlTableCell cellCssClass = new HtmlTableCell();
            rowCssClass.Controls.Add(cellCssClass);
            Label labelCssClass = new Label();
            labelCssClass.Text = "CSS classname";
            cellCssClass.Controls.Add(labelCssClass);
            cellCssClass.Controls.Add(new LiteralControl("<br />"));
            _cssClass = new TextBox();
            _cssClass.Width = 200;
            cellCssClass.Controls.Add(_cssClass);

            HtmlTableRow rowDebug = new HtmlTableRow();
            table.Controls.Add(rowDebug);
            HtmlTableCell cellDebug = new HtmlTableCell();
            rowDebug.Controls.Add(cellDebug);
            Label labelDebug = new Label();
            labelDebug.Text = "Run in debug mode";
            cellDebug.Controls.Add(labelDebug);
            _debug = new CheckBox();
            cellDebug.Controls.Add(_debug);

        }

        private void _selectList_Click(object sender, EventArgs e)
        {
            // just in WSS
            try
            {
                PopulateFields(string.Empty, string.Empty);
            }
            catch (Exception ex)
            {
                _error = ex;
            }
        }

        private void _listUrl_TextChanged(object sender, EventArgs e)
        {
            try
            {
                PopulateFields(string.Empty, string.Empty);
            }
            catch (Exception ex)
            {
                _error = ex;
            }
        }

        private void PopulateFields(string selectedDisplayField, string selectedValueField)
        {
            if (string.IsNullOrEmpty(_listUrl.Text))
                return;
            _selectDisplayField.Items.Clear();
            _selectDisplayField.Items.Add(new ListItem("-- Select a field --", ListItemFilter.EMPTYITEMVALUE));
            _selectValueField.Items.Clear();
            _selectValueField.Items.Add(new ListItem("-- Select a field --", ListItemFilter.EMPTYITEMVALUE));

            SPList list = ListSupport.GetList(_listUrl.Text);
            if (list == null)
            {
                throw new Exception(string.Format("No list found at url {0}.", _listUrl.Text));
            }
            bool displayItemFound = false;
            bool valueItemFound = false;
            foreach (SPField field in list.Fields)
            {
                if (!field.Hidden)
                {
                    ListItem item = new ListItem(field.Title, field.InternalName);
                    if (string.Compare(field.InternalName, selectedDisplayField, true) == 0)
                    {
                        displayItemFound = true;
                    }
                    _selectDisplayField.Items.Add(item);

                    ListItem valueItem = new ListItem(field.Title, field.InternalName);
                    if (string.Compare(field.InternalName, selectedValueField, true) == 0)
                    {
                        valueItemFound = true;
                    }
                    _selectValueField.Items.Add(valueItem);
                }
            }
            if (displayItemFound)
            {
                _selectDisplayField.SelectedValue = selectedDisplayField;
            }
            if (valueItemFound)
            {
                _selectValueField.SelectedValue = selectedValueField;
            }
        }

        public override void SyncChanges()
        {
            EnsureChildControls();
            ListItemFilter webPart = WebPartToEdit as ListItemFilter;
            if (webPart != null)
            {
                try
                {
                    _listUrl.Text = webPart.ListUrl;
                    PopulateFields(webPart.DisplayField, webPart.ValueField);
                    _selectDisplayMode.SelectedValue = webPart.DisplayMode.ToString();
                    _selectDistinct.Checked = webPart.SelectDistinct;
                    _cssClass.Text = webPart.ControlCssClass;
                    _debug.Checked = webPart.Debug;
                    if (_selectXSLT.Items.FindByValue(webPart.XsltStyleSheet)!=null)
                    {
                        _selectXSLT.SelectedValue = webPart.XsltStyleSheet;
                    }
                    _selectDisplayWebPartTitle.Checked = webPart.DisplayWebPartTitle;
                    _selectDropDownFirstItem.Text = webPart.DropDownFirstItem;
                }
                catch (Exception ex)
                {
                    _error = ex;
                }
            }
        }

        public override bool ApplyChanges()
        {
            EnsureChildControls();
            ListItemFilter webPart = WebPartToEdit as ListItemFilter;
            if (webPart != null)
            {
                webPart.ListUrl = _listUrl.Text;
                webPart.DisplayField = _selectDisplayField.SelectedValue;
                webPart.ValueField = _selectValueField.SelectedValue;
                int mode = 0;
                if (int.TryParse(_selectDisplayMode.SelectedValue, out mode))
                {
                    webPart.DisplayMode = mode;
                }
                webPart.SelectDistinct = _selectDistinct.Checked;
                webPart.ControlCssClass = _cssClass.Text;
                webPart.Debug = _debug.Checked;
                webPart.XsltStyleSheet = _selectXSLT.SelectedValue;
                webPart.DisplayWebPartTitle = _selectDisplayWebPartTitle.Checked;
                webPart.DropDownFirstItem = _selectDropDownFirstItem.Text;
            }
            return true;
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            string webLocale = SPContext.Current.Web.Locale.LCID.ToString();
            Page.ClientScript.RegisterClientScriptInclude("PickerTreeDialog", string.Format("/_layouts/{0}/PickerTreeDialog.js", webLocale));

            RegisterSelectListScript();
        }

        private void RegisterSelectListScript()
        {
            StringBuilder launchPicker = new StringBuilder();
            launchPicker.Append("<SCRIPT LANGUAGE='JavaScript' >");
            launchPicker.Append("function launchPicker()\n");
            launchPicker.Append("{\n");
            launchPicker.Append("   var listurlfield = document.getElementById(\"" + _listUrl.ClientID + "\");\n");
            launchPicker.AppendFormat("   var defaulturl = '{0}';\n", SPContext.Current.Web.ServerRelativeUrl);
            launchPicker.Append("   var url = defaulturl;\n");
            launchPicker.Append("   if(listurlfield != null && listurlfield.value != '')\n");
            launchPicker.Append("   {\n");
            launchPicker.Append("       url = listurlfield.value.substring(0,listurlfield.value.lastIndexOf('/'));");
            launchPicker.Append("   }\n");
            launchPicker.Append("   var callback=function(arr)\n");
            launchPicker.Append("   {\n");
            launchPicker.Append("       if(arr==null || arr==undefined)\n");
            launchPicker.Append("           return;\n");
            launchPicker.Append("       var site=arr[1];\n");
            launchPicker.Append("       var list=arr[2];\n");
            launchPicker.Append("       if(list != '')\n");
            launchPicker.Append("       {\n");
            launchPicker.Append("           listurlfield.value = site + (site == '/' ? '' : '/') + list;\n");
            launchPicker.Append("       }\n");
            launchPicker.Append("       " + Page.ClientScript.GetPostBackEventReference(_listUrl, string.Empty) + ";\n");
            launchPicker.Append("   }\n");
            launchPicker.Append("LaunchPickerTreeDialog(\'CbqPickerSelectListTitle','CbqPickerSelectListTitle','listsOnly',\"\",url,null,\"\",\"\",\"/_layouts/images/generic.png\", 0, callback );\n");
            launchPicker.Append("}\n");
            launchPicker.Append("</SCRIPT>");

            if (!Page.ClientScript.IsClientScriptBlockRegistered("launchPicker"))
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "launchPicker", launchPicker.ToString());
        }

        protected override void RenderContents(HtmlTextWriter writer)
        {
            if (_error != null)
            {
                writer.WriteLine(string.Format("<strong>Error:</strong> {0}.", _error.Message));
            }
            base.RenderContents(writer);
        }

    }
}
